<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\SubmittedTutorWWW;
use StudyBuddy\WebPage;
use StudyBuddy\TutorParser;
use StudyBuddy\Responder;

class Regtutor extends WebPage
{
	/**
	 * Pre-check to deny non-logged in user
	 * access to this page
	 *
	 * @var bool
	 */
	protected $membersOnly = true;


	/**
	 *
	 * Viewer must have edit_tutor
	 * permission to access this page
	 * @var string
	 */
	protected $permission = 'edit_tutor';


	/**
	 * $layoutID 1 means no side-column on page
	 *
	 * @var int
	 */
	protected $layoutID = 1;


	/**
	 * Form object
	 *
	 * @var object of type \StudyBuddy\Forms\Form
	 */
	protected $oForm;


	/**
	 * User object of user whose tutor
	 * is being edited
	 *
	 * @var object of type User
	 */
	protected $oUser;


	protected function main(){
		$this->getUser();
		$this->oForm = new \StudyBuddy\Forms\Tutor($this->oRegistry);
		$this->oForm->formTitle = $this->aPageVars['title'] = $this->_('Edit Tutor');

		if($this->oForm->isSubmitted() && $this->oForm->validate()){
			$this->oRegistry->Dispatcher->post($this->oForm, 'onBeforeTutorUpdate');
			//try{
				$this->saveTutor();
				$this->oRegistry->Dispatcher->post($this->oForm, 'onTutorUpdate');
				$amount = ($this->oForm->getSubmittedValue('package')=='a') ? 2 : 3;
				$this->aPageVars['body'] = \tplTutorSuccess::parse(array('Tutor has been updated', '', 'View the new tutor', $amount), false);
				Responder::redirectToPage('/users/' . $this->oRequest->get('uid', 'i', null) . '/' . $this->oRequest->get('username'));
			/*} catch (\StudyBuddy\Exception $e){
				$this->oForm->setFormError($e->getMessage());
				$this->setForm();
				$this->aPageVars['body'] = $this->oForm->getForm();
			}*/
		} else {
			$this->setForm();
			$this->aPageVars['body'] = $this->oForm->getForm();
		}
	}


	/**
	 * Create $this->oUser User object for user whose
	 * tutor is being edited
	 *
	 * @todo unfinished. IT will be possible to
	 * edit user other than Viewer when Viewer has
	 * permission to edit_other_tutor
	 * For now this is a Viewe object
	 *
	 * @return object $this
	 */
	protected function getUser(){
		$uid = $this->oRequest->get('uid', 'i', null);
		if($uid && ($uid !== $this->oRegistry->Viewer->getUid())){
			/**
			 * This is edit tutor for another user
			 * check Viewer permission here
			 */
			$this->checkAccessPermission('edit_any_tutor');
			$this->oUser = \StudyBuddy\User::factory($this->oRegistry)->by_id($uid);
		} else {
			$this->oUser = $this->oRegistry->Viewer;
		}

		return $this;
	}


	/**
	 * Populate form elements with
	 * values from current user tutor
	 *
	 * @return object $this
	 */
	protected function setForm(){

		$this->oForm->tmp_role = $this->getRoleInput();
                $this->oForm->new_reg = 'display:none';
                if(!isset($this->oRegistry->Viewer['tmp_role'])) {
                    if($this->oRegistry->Viewer['role'] == 'unactivated') {
                        $this->oForm->new_reg = '';
                    } else {
                        //
                    }
                } else {
                    if($this->oRegistry->Viewer['tmp_role'] == 'tutor') {
                        // 
                    } else {
                        // 
                        $this->oForm->js_redirect = '<script type="text/javascript">window.location=\'http://'.$_SERVER['HTTP_HOST'].'/editprofile/\';</script>';
                    }
                } 
//		$this->oForm->new_reg = '';
		$this->oForm->old_reg = 'display:none';
		$this->oForm->tmp_role_display = $this->getRoleInput1();
		$this->oForm->package = $this->getPackageInput();
		$this->oForm->niecert = $this->getNiecert();
		$this->oForm->qualification = $this->getQualification();
		$this->oForm->teach = $this->getTeach();
                
		$this->oForm->username = $this->oUser['username'];
		$this->oForm->usernameLabel = 'Username';
		$this->oForm->fn = $this->oUser['fn'];
		$this->oForm->mn = $this->oUser['mn'];
		$this->oForm->ln = $this->oUser['ln'];
		$this->oForm->fullname = $this->oUser['fullname'];
		$this->oForm->mobile = $this->oUser['mobile'];
		$this->oForm->experience = $this->oUser['experience'];
		$this->oForm->gender = '';
		$this->oForm->dob = $this->oUser['dob'];
		$this->oForm->cc = '';
		$this->oForm->state = $this->oUser['state'];
		$this->oForm->city = $this->oUser['city'];
		$this->oForm->url = $this->oUser['url'];
		$this->oForm->zip = $this->oUser['zip'];
		$this->oForm->description = $this->oUser['description'];
		$this->oForm->sowa = $this->oUser['sowa'];
		$this->oForm->avatarSrc = $this->oUser->getAvatarSrc();
		$this->oForm->width = $this->oRegistry->Ini->AVATAR_SQUARE_SIZE;
		$this->oForm->uid = $this->oUser->getUid();
		$this->oForm->maxAvatarSize = $this->oRegistry->Ini->MAX_AVATAR_UPLOAD_SIZE;
		/**
		 * @todo translate string
		 */
		$this->oForm->avatarTos = sprintf('Upload Image. Maximum size of %sMb<br><span class="smaller">By uploading a file you certify that you have the right to distribute this picture and that it does not violate the Terms of Service.</span>', floor($this->oRegistry->Ini->MAX_AVATAR_UPLOAD_SIZE / 1000000) );

		/**
		 * Add '  hide' class to avatar upload
		 * if php does not have gd of support for jpeg
		 * inside gd
		 */
		if(!\extension_loaded('gd') || !\function_exists('imagecreatefromjpeg')){
			$this->oForm->hideAvatar = ' hide';
		}

		return $this;
	}


	/**
	 * Save changed to user tutor
	 * using TutorParser class
	 *
	 * @return object $this
	 */
	protected function saveTutor(){

		TutorParser::factory($this->oRegistry)->save($this->oUser, new SubmittedTutorWWW($this->oForm));

		/**
		 * Should unset 'welcome' from session
		 * because it contains user display name in the
		 * link and display name may have changed as a
		 * result of editing first, middle and last names
		 */
		unset($_SESSION['welcome']);

		return $this;
	}


        protected function getRoleInput(){
            $current = 'tutor';
            if(isset($this->oRegistry->Viewer['tmp_role'])) {
                $current = $this->oRegistry->Viewer['tmp_role'];
            } 
            
            $s = '';
            $a = array('student' => 'Student', 'parent' => 'Parent', 'tutor' => 'Tutor');
            $tpl = '<input type="radio" id="id_role%1$s" name="tmp_role"%2$s value="%3$s"%4$s /> %5$s ';
            $i = 1;
            foreach ($a as $key => $value){
                $checked = ($key == $current) ? ' checked="checked"' : '';
                //$disabled = ($key == $current) ? '' : ' disabled="disabled"';
                $tutor = ($key == 'student' || $key == 'parent') ? 'onclick="window.location=\'http://'.$_SERVER['HTTP_HOST'].'/editprofile/\'"' : '';
                $s .= vsprintf($tpl, array($i, $tutor, $key, $checked, $value));
                $i++;
            }
            return $s;
        }
		
		protected function getRoleInput1(){
            $current = $this->oRegistry->Viewer['role'];
            $current = ($current != 'parent' && $current != 'tutor') ? 'student' : $current;
            return strtoupper($current);
        }
        
        protected function getPackageInput(){
            $current = 'a';
            $s = '';
            $a = array('a' => 'Package A', 'b' => 'Package B');
            $tpl = '<input type="radio" id="id_package%1$s" name="package" value="%2$s"%3$s /> %4$s ';
            $i = 1;
            foreach ($a as $key => $value){
                $checked = ($key == $current) ? ' checked="checked"' : '';
                $s .= vsprintf($tpl, array($i, $key, $checked, $value));
                $i++;
            }
            return $s;
        }
        
        protected function getNiecert(){
		$current = $this->oRegistry->Viewer['niecert'];
		$s = '';
		$a = array('' => 'Select NIE Cert', '1' => 'Yes', '2' => 'No');
		$tpl = '<option value="%1$s"%2$s>%3$s</option>';
		foreach($a as $key => $val){
			$selected = ($key == $current) ? ' selected="selected"' : '';
			$s .= vsprintf($tpl, array($key, $selected, $val));
		}

		return $s;
	}
        
        protected function getQualification(){
		$current = $this->oRegistry->Viewer['qualification'];
		$s = '';
		$a = array('' => 'Select Qualification', '1' => 'O Level', '2' => 'N Level', '3' => 'Diploma', '4' => 'Degree', '5' => 'Masters', '6' => 'PhD');
		$tpl = '<option value="%1$s"%2$s>%3$s</option>';
		foreach($a as $key => $val){
			$selected = ($key == $current) ? ' selected="selected"' : '';
			$s .= vsprintf($tpl, array($key, $selected, $val));
		}

		return $s;
	}
        
        protected function getTeach(){
            $subject = array('English', 'Maths', 'A Maths', 'Science', 'Physics', 'Chemistry', 'Biology', 'Geography', 'History', 'Literature');
            $a = explode(',', $this->oRegistry->Viewer['teach']);
            if($a[0]=='') {
                for($i=0; $i<100; $i++){
                    $a[$i] = 0;
                }
                
            }
            $s = '';
            $tpl_s = '<%1$s class="%2$s"><td>%3$s</td>';
            $tpl_e = '</%1$s>';
            $tpl = '<td><input type="checkbox" name="sj%1$s" value="1"%2$s /></td>';
            
            for($i=0; $i<100;$i++) {
                if($i==0){
                    $s .= vsprintf($tpl_s, array('tr', 'old', $subject[floor($i/10)]));
                } else if($i%10==0) {
                    $s .= vsprintf($tpl_e, array('tr'));
                    $even_old = ($i%2==0) ? 'old' : 'even';
                    $s .= vsprintf($tpl_s, array('tr', $even_old, $subject[floor($i/10)]));
                }
                $checked = isset($a[$i]) ? ($a[$i] == 0) ? '' : ' checked="checked"' : '';
                $s .= vsprintf($tpl, array($i, $checked));
                if($i==99){
                    $s .= vsprintf($tpl_e, array('tr'));
                }
            }
            
            return $s;
        }

}
